/**
 * 获取字符串中子串的所有位置
 * @param sourceStr
 * @param subStr
 * @returns {*[]} 索引值数组, 没有匹配到则返回空数组
 */
function getIndexArray(sourceStr, subStr) {
    if (!sourceStr || sourceStr.length === 0 || !subStr || subStr.length === 0) {
        return []
    }

    let indexArray = []
    let nextIndexValue = 0
    while (true) {
        nextIndexValue = sourceStr.indexOf(subStr, nextIndexValue)
        if (nextIndexValue < 0) {
            break
        } else {
            indexArray.push(nextIndexValue)
            nextIndexValue++
        }
    }
    return indexArray
}

/**
 * 对字符串中的所有指定字串后插入字符串
 * 例:   传入  sourceStr:`<img></img><img></img>`     targetStr:`<img`     insertStr:` style=max-width:90% ` (前后有空格)
 * 返回:  `<img style=max-width:90% ></img><img style=max-width:90% ></img>`
 * @param sourceStr 原本的字符串
 * @param targetStr 匹配的字符串
 * @param insertStr 需插入的字符串
 * @returns {*} 处理后的结果字符串
 */
function insertStrAfterTarget(sourceStr, targetStr, insertStr) {
    let indexArray = getIndexArray(sourceStr, targetStr)
    if (indexArray.length === 0) {
        return sourceStr
    }

    let resultStr = sourceStr

    // 索引位置偏移量, 每插入一个字符串, 其后的索引位置需相应地修改
    let offsetValue = insertStr.length
    // 插入的位置
    let addIndex = 0

    for (let i = 0; i < indexArray.length; i++) {
        addIndex = indexArray[i] + offsetValue * i + targetStr.length
        // 分割字符串并在中间插入
        resultStr = resultStr.slice(0, addIndex) + insertStr + resultStr.slice(addIndex)
    }
    return resultStr
}

function insertStrBeforeTarget(sourceStr, targetStr, insertStr) {
    let indexArray = getIndexArray(sourceStr, targetStr)
    if (indexArray.length === 0) {
        return sourceStr
    }

    let resultStr = sourceStr

    // 索引位置偏移量, 每插入一个字符串, 其后的索引位置需相应地修改
    let offsetValue = insertStr.length
    // 插入的位置
    let addIndex = 0

    for (let i = 0; i < indexArray.length; i++) {
        addIndex = indexArray[i] + offsetValue * i
        // 分割字符串并在中间插入
        resultStr = resultStr.slice(0, addIndex) + insertStr + resultStr.slice(addIndex)
    }
    return resultStr
}
